<?php

namespace app\model;

use think\Model;
use think\model\relation\HasOne;

class AccountApply extends Model
{
    public function account(): HasOne
    {
        return $this->hasOne(Account::class, 'id', 'aid');
    }

    public function store(): HasOne
    {
        return $this->hasOne(Account::class, "id", "sid");
    }

    public function getPage(): array
    {
        $param = request()->param();
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 50;
        if (!empty($param['pid'])) {
            $param['sid'] = app(Account::class)->where(['supplier_id' => $param['pid']])->column("id");
        }
        $data = $this->with(['account', 'store'])->when(!empty($param['state']), function ($query) use ($param) {
            $query->where('state', $param['state']);
        })->when(!empty($param['create_time']), function ($query) use ($param) {
            $query->whereBetween('create_time', [$param['create_time'][0] . " 00:00:00", $param['create_time'][1] . " 23:59:59"]);
        })->when(!empty($param['sid']), function ($query) use ($param) {
//            dd($param['sid']);
            $query->whereIn('sid', $param['sid']);
        })->when(!empty($param['aid']), function ($query) use ($param) {
            $query->where('aid', $param['aid']);
        })->order(['create_time' => 'desc'])->paginate(['list_rows' => $limit, 'page' => $page])->toArray();
        return ['lst' => $data['data'], 'total' => $data['total'], 'totalPage' => $data['last_page']];
    }

    public function download(): array
    {
        $data = $this->getPage();
        $result = array_map(function ($item) {
            return [
                $item['account']['name'],
                $item['store']['name'],
                ($item['state'] == 1 ? '+' : '-') . bcdiv($item['number'], 100, 2),
                $item['create_time'],
            ];
        }, $data['lst']);
        $header = ['店员', '店长', '金额', '申请时间'];
        $title = ["门店授权记录"];
        $file = "门店授权记录";
        $totalPage = $data['totalPage'];
        return compact("result", "header", "title", "totalPage", "file");
    }
}
